package com.demandbreakdown.xiyun.controller;

import com.demandbreakdown.xiyun.common.annotation.ApiLog;
import com.demandbreakdown.xiyun.common.base.Result;
import com.demandbreakdown.xiyun.common.base.ResultUtils;
import com.demandbreakdown.xiyun.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统健康检查控制器
 *
 * @author poxz
 */
@RestController
@RequestMapping("/health")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "健康检查", description = "系统健康检查接口")
public class HealthController {

    private final DataSource dataSource;
    private final RedisTemplate<String, Object> redisTemplate;
    private final UserMapper userMapper;

    /**
     * 系统健康检查
     */
    @ApiLog("系统健康检查")
    @Operation(summary = "系统健康检查", description = "检查数据库、Redis等关键组件的连接状态")
    @GetMapping
    public Result<Map<String, Object>> healthCheck() {
        Map<String, Object> healthInfo = new HashMap<>();
        boolean allHealthy = true;

        // 检查数据库连接
        try {
            try (Connection connection = dataSource.getConnection()) {
                boolean isValid = connection.isValid(5);
                healthInfo.put("database", Map.of(
                        "status", isValid ? "UP" : "DOWN",
                        "details", isValid ? "数据库连接正常" : "数据库连接异常"
                ));
                if (!isValid) allHealthy = false;

                // 测试MyBatis查询
                long userCount = userMapper.selectCount(null);
                healthInfo.put("mybatis", Map.of(
                        "status", "UP",
                        "details", "MyBatis查询正常，用户总数: " + userCount
                ));
            }
        } catch (Exception e) {
            log.error("数据库健康检查失败", e);
            healthInfo.put("database", Map.of(
                    "status", "DOWN",
                    "details", "数据库连接失败: " + e.getMessage()
            ));
            healthInfo.put("mybatis", Map.of(
                    "status", "DOWN",
                    "details", "MyBatis查询失败: " + e.getMessage()
            ));
            allHealthy = false;
        }

        // 检查Redis连接
        try {
            redisTemplate.opsForValue().set("health:check", "ok");
            String value = (String) redisTemplate.opsForValue().get("health:check");
            boolean redisHealthy = "ok".equals(value);
            healthInfo.put("redis", Map.of(
                    "status", redisHealthy ? "UP" : "DOWN",
                    "details", redisHealthy ? "Redis连接正常" : "Redis连接异常"
            ));
            if (!redisHealthy) allHealthy = false;
            redisTemplate.delete("health:check");
        } catch (Exception e) {
            log.error("Redis健康检查失败", e);
            healthInfo.put("redis", Map.of(
                    "status", "DOWN",
                    "details", "Redis连接失败: " + e.getMessage()
            ));
            allHealthy = false;
        }

        // 总体状态
        healthInfo.put("overall", Map.of(
                "status", allHealthy ? "UP" : "DOWN",
                "timestamp", System.currentTimeMillis()
        ));

        return ResultUtils.success(healthInfo);
    }

    /**
     * 简单的健康检查（只返回状态）
     */
    @ApiLog("简单健康检查")
    @Operation(summary = "简单健康检查", description = "简单的存活检查")
    @GetMapping("/simple")
    public Result<String> simpleHealthCheck() {
        return ResultUtils.success("OK");
    }
}
